﻿CREATE TRIGGER yaf_UserGroup_insert
ON dbo.yaf_UserGroup
FOR INSERT
AS
    BEGIN
        DECLARE  @UserID INT
        DECLARE  @BoardID INT
        DECLARE  @GroupID INT
        DECLARE  @Flags INT
        DECLARE inserted_cursor CURSOR  FOR
        SELECT a.UserID,
               b.BoardID,
               b.GroupID,
               b.Flags
        FROM   inserted a
               JOIN dbo.yaf_Group b
                 ON b.GroupID = a.GroupID
        OPEN inserted_cursor
        FETCH NEXT FROM inserted_cursor
        INTO @UserID,
             @BoardID,
             @GroupID,
             @Flags
        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF (@Flags & 2) <> 0
            BEGIN
                -- This is the guest group. Check for guest users
                IF EXISTS (SELECT 1
                           FROM   dbo.yaf_UserGroup
                           WHERE  GroupID = @GroupID
                           AND UserID <> @UserID)
                BEGIN
                    RAISERROR ('There is already a user in the guest group',16,1)
                END
            END
            FETCH NEXT FROM inserted_cursor
            INTO @UserID,
                 @BoardID,
                 @GroupID,
                 @Flags
        END
        CLOSE inserted_cursor
        DEALLOCATE inserted_cursor
    END


